class Restaurant < ApplicationRecord
    has_attached_file :attachment,
                    path: ":rails_root/public/uploads/restaurants/:id/:basename.:extension",
                    url: "/uploads/restaurants/:id/:basename.:extension"
    has_many :food_types,dependent: :destroy
    has_many :food_groups,dependent: :destroy
    has_many :drinks,dependent: :destroy
    has_many :discount_foods,dependent: :destroy
    has_one :discount_setting,dependent: :destroy    
    has_many :orders,dependent: :destroy
    has_many :cars,dependent: :destroy
    has_many :restaurant_messages,dependent: :destroy
    has_many :printers
    validates_attachment_content_type :attachment, content_type: /\Aimage\/.*\Z/
    validates :login,presence: true,uniqueness: true
    validates :name,presence: true
    

  def password
    @password
  end

  def password=(pass)
    return unless pass
    @password = pass
    generate_password(pass)
  end


  def self.authentication(login,password)
    user = Restaurant.find_by_login(login)
    if user && Digest::SHA256.hexdigest(password + user.salt) == user.password_hash
      return user
    end
    false
  end

  def authentication_password(password)
    if self.password_hash == Digest::SHA256.hexdigest(password + self.salt)
      true
    else
      false
    end
  end

  private
  def generate_password(pass)
    salt = Array.new(10) { rand(1024).to_s(36)}.join
    self.salt, self.password_hash =
        salt,Digest::SHA256.hexdigest(pass+salt)
  end
end
